package com.lwq.im.chartdemo.endecode;

import com.lwq.im.chartdemo.bean.IMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 消息编码
 */
@Slf4j
public class MessageEncoder extends MessageToMessageEncoder<IMessage> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, IMessage message, List<Object> list) throws Exception {

        log.info("通道{}编码",channelHandlerContext.channel().id());

        byte[] body = message.getBody();
        ByteBufAllocator allocator = channelHandlerContext.channel().config().getAllocator();
        ByteBuf buffer = allocator.buffer(body.length + 1);
        buffer.writeByte(message.getMsgType());
        buffer.writeBytes(body);
        list.add(new BinaryWebSocketFrame(buffer));
    }
}
